class Cart {
	constructor() {
		this.stateAll = false
		this.tableEle = document.querySelector('table')
		this.totalPriceEle = document.querySelector('.total-price>span')
		this.addProductEle = document.querySelector('.container .add-product')
	}

	/**
	 * 动态渲染localStorage商品数组数据
	 * 	 1. 获取localStorage商品数组
	 *
	 */
	showProductList() {
		//1. 获取localStorage商品数组
		let cartListStr = localStorage.getItem('CART-LIST-2203')
		let cartList = JSON.parse(cartListStr) || []

		//2.拼接table字符串
		let str = `<tr>
					<th><input type="checkbox" name="checkall" ${item.stateAll ? 'checked' : ''}>全选</th>
					<th>商品图片</th>
					<th>商品信息</th>
					<th>单价</th>
					<th>数量</th>
					<th width="100px">总价</th>
					<th>操作</th>
				</tr>`

		let trStr = cartList
			.map(item => {
				return `<tr>
						<td><input type="checkbox" name="checksingle" ${item.state ? 'checked' : ''} data-index="${item.id}"></td>
						<td><img src="${item.url}" alt="p1" /></td>
						<td>${item.name}</td>
						<td>￥${item.price}</td>
						<td>
							<input type="button" value="-" name="minus" data-index="${item.id}" ${item.num == 0 ? 'disabled' : ''}/>
							<input type="text" value="${item.num}" name="amount" />
							<input type="button" value="+" name="plus" data-index="${item.id}"/>
						</td>
						<td class="all-price">￥${item.singlePrice}</td>
						<td>
							<a href="#">移入收藏</a><br />
							<a href="#" class="del" data-index="${item.id}">删除</a>
						</td>
					</tr>`
			})
			.join('')
		str += trStr

		this.tableEle.innerHTML = str
	}

	/**
	 * 添加商品
	 *   1. 点击添加按钮
	 *   2. 获取表单数据
	 *   3. 生成商品对象
	 */
	onAddProduct() {
		const form = document.querySelector('form')
		const nameEle = document.querySelector('input[name="name"]')
		const priceEle = document.querySelector('input[name="price"]')
		// const numEle = document.querySelector('input[name="num"]')
		const urlEle = document.querySelector('input[name="url"]')

		// 1. 点击添加按钮
		form.addEventListener('submit', e => {
			e = e || window.event //事件对象
			e.preventDefault() //阻止默认行为

			//2. 获取表单数据
			let [id, name, price, num, url] = [this.getRandom(1000, 10000), nameEle.value, priceEle.value, 0, urlEle.value]

			if (!this.checkUrlNull(url)) {
				return
			}
			if (!this.checkNameNull(name)) {
				return
			}
			if (!this.checkPriceNull(price)) {
				return
			}
			// if (!this.checkNumNull(num)) {
			// 	return
			// }
			if (isNaN(price)) {
				alert('价格必须为数字')
				return
			}
			//3. 生成商品对象
			let product = {
				id,
				name,
				url,
				price,
				num,
				singlePrice: (num * price).toFixed(2),
				state: false, //状态
			}

			//4.持久化存储商品对象到loalStorage
			let cartListStr = localStorage.getItem('CART-LIST-2203')
			let cartList = JSON.parse(cartListStr) || []

			cartList.push(product)

			localStorage.setItem('CART-LIST-2203', JSON.stringify(cartList))

			//5.重新渲染页面
			this.showProductList()
			this.onTotalPrice()
			nameEle.value = ''
			priceEle.value = ''
			// numEle.value = ''
			urlEle.value = ''
			this.addProductEle.classList.add('hidden')
		})
	}

	onCancel() {
		const cancelEle = document.querySelector('.container .add-product form input[type="button"]')
		const nameEle = document.querySelector('input[name="name"]')
		const priceEle = document.querySelector('input[name="price"]')
		// const numEle = document.querySelector('input[name="num"]')
		const urlEle = document.querySelector('input[name="url"]')
		cancelEle.addEventListener('click', () => {
			this.addProductEle.classList.add('hidden')
			nameEle.value = ''
			priceEle.value = ''
			// numEle.value = ''
			urlEle.value = ''
		})
	}

	/**
	 * 操作购物车
	 */
	onProduct() {
		this.tableEle.addEventListener('click', e => {
			e = e || window.event //事件对象
			let target = e.target || e.srcElement //事件目标对象
			if (target.getAttribute('class') == 'del') {
				let id = target.getAttribute('data-index')
				//删除localStorage中商品
				let cartListStr = localStorage.getItem('CART-LIST-2203')
				let cartList = JSON.parse(cartListStr) || []
				//findIndex 遍历数组，找满足条件的元素索引号
				let index = cartList.findIndex(item => item.id == id)
				cartList.splice(index, 1)
				localStorage.setItem('CART-LIST-2203', JSON.stringify(cartList))

				//重新渲染页面
				this.showProductList()
				this.onTotalPrice()
			}
			//加一
			/**
			 *  1. 获取id
			 *  2. 找商品对象
			 */
			if (target.getAttribute('value') == '+') {
				//获取id
				let id = target.getAttribute('data-index')

				let cartListStr = localStorage.getItem('CART-LIST-2203')
				let cartList = JSON.parse(cartListStr) || []
				//查找商品
				// let product = cartList.find(item => item.id == id)
				let index = cartList.findIndex(item => item.id == id)
				//数量加一
				// 
				cartList[index].num++
				//计算价格
				cartList[index].singlePrice = (cartList[index].num * cartList[index].price).toFixed(2)

				localStorage.setItem('CART-LIST-2203', JSON.stringify(cartList))

				//重新渲染商品列表
				this.showProductList()

				//计算总价
				this.onTotalPrice()
			}
			/**
			 * 减操作
			 */
			if (target.getAttribute('value') == '-') {
				//获取id
				let id = target.getAttribute('data-index')

				let cartListStr = localStorage.getItem('CART-LIST-2203')
				let cartList = JSON.parse(cartListStr) || []
				//查找商品
				let product = cartList.find(item => item.id == id)
				//数量减一
				product.num--

				//计算价格
				product.singlePrice = (product.num * product.price).toFixed(2)

				localStorage.setItem('CART-LIST-2203', JSON.stringify(cartList))
				//重新渲染商品列表
				this.showProductList()

				//计算总价
				this.onTotalPrice()
			}
			/**
			 *  全选功能
			 *     点击全选框，将所有商品对应的复选框选中
			 *       1. 全选框点击事件
			 *       2. 将所有商品对应的复选框选中
			 */
			if (target.getAttribute('name') == 'checkall') {
				// 设置全选框状态
				this.stateAll = !this.stateAll

				let cartListStr = localStorage.getItem('CART-LIST-2203')
				let cartList = JSON.parse(cartListStr) || []

				//设置所有商品state状态为true
				cartList.forEach(item => (item.state = this.stateAll))

				localStorage.setItem('CART-LIST-2203', JSON.stringify(cartList))

				//重新渲染商品列表
				this.showProductList()
				this.onTotalPrice()
			}
			/**
			 * 单选功能
			 *   点击单选框，判断所有商品状态是否选中，如果全选中，则全选框选中
			 *                                     只要有一个未选中，则全选框不选中
			 *
			 */
			if (target.getAttribute('name') == 'checksingle') {
				//判断所有商品状态是否选中，如果全选中，则全选框选中
				/**
				 * 设置单选框状态
				 *    1. 查找单选框 
				 *    2. 改变state状态
				 */
				let id = target.getAttribute('data-index')
				let cartListStr = localStorage.getItem('CART-LIST-2203')
				let cartList = JSON.parse(cartListStr) || []
				let product = cartList.find(item => item.id == id)
				product.state = !product.state

				//设置全选框状态
				this.stateAll = cartList.every(item => item.state == true)

				localStorage.setItem('CART-LIST-2203', JSON.stringify(cartList))
				//重新渲染商品列表
				this.showProductList()
				this.onTotalPrice()
			}
		})
	}

	onAddButton() {
		const addButtonEle = document.querySelector('.container .logo input')
		addButtonEle.addEventListener('click', () => {
			this.addProductEle.classList.remove('hidden')
		})
	}
	/**
	 * 获取m-n之间的随机数
	 * @param {*} m
	 * @param {*} n
	 * @returns
	 */
	getRandom(m, n) {
		var max = Math.max(m, n)
		var min = Math.min(m, n)
		return Math.floor(Math.random() * (max - min) + min)
	}

	onTotalPrice() {
		//计算总价
		let cartListStr = localStorage.getItem('CART-LIST-2203')
		let cartList = JSON.parse(cartListStr) || []

		let sum = cartList.reduce((previousValue, currentItem) => currentItem.state ? previousValue + Number(currentItem.singlePrice) : previousValue, 0)

		//将总价赋值显示
		this.totalPriceEle.innerHTML = `￥${sum.toFixed(2)}`
	}
	checkNameNull(name) {
		if (name == '') {
			alert('商品名称不能为空')
			return false
		} else {
			return true
		}
	}
	checkUrlNull(url) {
		if (url == '') {
			alert('商品图片不能为空')
			return false
		} else {
			return true
		}
	}
	checkPriceNull(price) {
		if (price == '') {
			alert('商品价格不能为空')
			return false
		} else {
			return true
		}
	}
	checkNumNull(num) {
		if (num == '') {
			alert('商品数量不能为空')
			return false
		} else {
			return true
		}
	}
}

let cart = new Cart()
cart.showProductList()
cart.onAddProduct()
cart.onProduct()
cart.onTotalPrice()
cart.onAddButton()
cart.onCancel()

